package com.dsteiner.widgets.server.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.dsteiner.widgets.client.event.DataUpdateEvent;
import com.dsteiner.widgets.client.event.EventListener;
import com.dsteiner.widgets.client.rpc.SearchResult;

public interface CacheUtil {

	public static class CacheUtilMap implements CacheUtil{

		private static CacheUtil instance;

		public static CacheUtil getInstance() {
			if (instance == null)
				instance = new CacheUtilMap();
			return instance;
		}
		
		private Cache cache;
		
		private CacheUtilMap(){
		}
		
		public void clear() {
			getCache().clear();
		}

		public Object getCacheValue(Object cacheName, Object parameter) {
			Map cacheMap = getCacheMap(cacheName);
			return cacheMap.get(parameter);
		}

		public void setCacheValue(Object cacheName, Object parameter, Object value) {
			Map cacheMap = getCacheMap(cacheName);
			cacheMap.put(parameter, value);
			getCache().put(cacheName, cacheMap);
		}

		private Cache getCache(){
			if(cache == null){
				try {
					CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
					cache = cacheFactory.createCache(Collections.emptyMap());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return cache;
		}

		private Map getCacheMap(Object cacheName) {
			Map cacheMap = (Map) getCache().get(cacheName);
			if(cacheMap == null){
				cacheMap = new HashMap();
			}
			return cacheMap;
		}

		public Object getCache(String cacheName) {
			return getCacheMap(cacheName);
		}

		public void removeCacheValue(Object cacheName, Object parameter) {
			Map cacheMap = getCacheMap(cacheName);
			cacheMap.remove(parameter);
			getCache().put(cacheName, cacheMap);
		}
	}
	
	void clear();

	Object getCacheValue(Object cacheName, Object parameter);

	void setCacheValue(Object cacheName, Object parameter, Object value);

	Object getCache(String cacheName);

	void removeCacheValue(Object cacheName, Object parameter);
}
